const express = require('express');
const path = require('path');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

var usocket = [];
var count = 0;
var userList = [];
var msgList = [];

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// 监听用户连接
io.on('connection', socket => {
  count += 1;
  // 人员增加
  io.emit('population', count);
  console.log('a user connected', count);
  // 新用户进入 发送历史聊天记录 服务重启丢失
  io.emit('history', msgList);

  // 监听join
  socket.on('join', nickName => {
    usocket[nickName] = socket;
    userList.push(nickName);
    //  服务器通过广播将新加入的用户发送给在线成员
    io.emit('join', nickName);
    io.emit('updateConcatenation', userList);
  });

  // 监听消息
  socket.on('message', (msg, nickName) => {
    if (msgList.length > 50) {
      msgList.unshift();
    }
    msgList.push(`${nickName}: ${msg}`);
    io.emit('message', msg, nickName);
  });

  //  监听人数
  socket.on('downsizing', nickName => {
    if (count > 0) {
      count -= 1;
    }
    userList = userList.filter(x => x !== nickName);
    io.emit('population', count);
    io.emit('leave', nickName);
    io.emit('updateConcatenation', userList);
  });
});

http.listen(7000, function () {
  console.log('listen on *: 7000');
});
